package team.nmsg.ge.system.controller;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import team.nmsg.auto.TestLog;
import team.nmsg.ge.system.bean.PageObject;
import team.nmsg.ge.system.init.CommonDefine;
import team.nmsg.ge.system.service.ITestLogService;
import team.nmsg.ge.system.util.SysLanguageHelper;
@CrossOrigin
@RestController
@RequestMapping("tlog")
public class TestLogController extends BaseController{
	
	private static Logger logger =  LoggerFactory.getLogger(  SystemController.class );
	
	@Autowired
	private ITestLogService logSer;
	
	@RequestMapping("addlog")
	public String addLog(  HttpServletRequest request ) {
		JSONObject obj= new JSONObject();
		
		
		String datas = request.getParameter("datas"); 
		JSONObject parseObject = JSONObject.parseObject(datas);
		String logStr = parseObject.getString("log");
		
		TestLog toSave = JSONObject.parseObject(logStr,  TestLog.class);
		
		TestLog a = logSer.saveLog(toSave);
		if( a!=null ) {
			obj.put("res", true );
		}else {
			obj.put("res", false );
		}
		
		return obj.toString();
	}

	@RequestMapping("/tlogs")
	public ModelAndView systemLog() {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<Integer, String> logTypes = CommonDefine.logTypeToDesc;
		data.put("logTypes", logTypes);
		ModelAndView mv = new ModelAndView("auto/TestLog", data);
		return mv;
	}

	@RequestMapping("/queryLogs")
	public String queryLogs(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		String sEcho = req.getParameter("sEcho");
		String startIndex = req.getParameter("iDisplayStart");
		String pageSize = req.getParameter("iDisplayLength");
		String username = req.getParameter("username");
		String startTime = req.getParameter("StartTime");
		String endTime = req.getParameter("EndTime");
		String sn = req.getParameter("SN");
		int logType = Integer.valueOf(req.getParameter("logType"));
		String testType = req.getParameter("testType");
		long _startTime = 0;
		long _endTime = 0;
		if (startTime != null && !"".equals(startTime)) {
			_startTime = convertLogTime(startTime);
		}
		if (endTime != null&& !"".equals(endTime)) {
			_endTime = convertLogTime(endTime);
		}

		TestLog logBean = new TestLog();
		logBean.setUser(username);
		logBean.setDevSn(sn);
		logBean.setType(logType);
		logBean.setTesttype(testType);
		PageObject<TestLog> page = logSer.queryLogs(
				Integer.parseInt(pageSize), Integer.parseInt(startIndex),
				logBean, _startTime, _endTime);

		JSONArray arr = new JSONArray();
		for (TestLog log : page.getCurrentEntitys()) {
			JSONObject json = log.toJson();
			arr.add(json);
		}
		obj.put("aaData", arr);
		obj.put("sEcho", sEcho);
		obj.put("iTotalRecords", page.getSumCount());
		obj.put("iTotalDisplayRecords", page.getSumCount());
		writeJson(obj, resp);
		return null;

	}
	
	private long convertLogTime(String time){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String st1 = time.substring(0, 10);
		String st2 = time.substring(13);
		time = st1 + " " + st2;
		try {
			Date date = sdf.parse(time);
			return date.getTime();
		} catch (ParseException e) {
			logger.error(" TestLogControllerExceptionHandler ::: ", e);
		}
		return 0;
	}
	@RequiresPermissions("DelTestLog")
	@RequestMapping("/deleteLogByID")
	public String deleteLogByID(HttpServletRequest req,  HttpServletResponse resp){
		JSONObject obj = new JSONObject();
		String[] logIds = req.getParameterValues("logId[]");
		try {
			boolean result=logSer.deleteLogById(logIds);
			obj.put("result", result);
		} catch (Exception e) {
			logger.error(" SystemControllerExceptionHandler ::: " , e );
		}
		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("queryBaseLogsBySn")
	public String queryBaseLogsBySn(HttpServletRequest req,  HttpServletResponse resp){
		JSONObject obj = new JSONObject();
		String datas = req.getParameter("datas"); 
		JSONObject parseObject = JSONObject.parseObject(datas);
		String sn = parseObject.getString("SN");
		obj.put("logList", logSer.queryBaseLogsBySn(sn));
		writeJson(obj, resp);
		return null;
	}
	
	@RequestMapping("backUpAllAlert")
	public String backUpAllAlert(HttpServletRequest req,  HttpServletResponse resp){
		try {
			String fileName = System.currentTimeMillis()+"_testLog.xls";
			String devSn = req.getParameter("SN");
			String startTime = req.getParameter("StartTime");
			String endTime = req.getParameter("EndTime");
			String username = req.getParameter("username");
			int logType = Integer.valueOf(req.getParameter("logType"));
			String testType = req.getParameter("testType");
			int pageNo = Integer.parseInt( req.getParameter("pageNo") );
			int pageSize = Integer.parseInt( req.getParameter("pageSize") );
			
			long _startTime = 0;
			long _endTime = 0;
			
			if (startTime != null && !"".equals(startTime)) {
				_startTime = convertLogTime(startTime);
			}
			if (endTime != null&& !"".equals(endTime)) {
				_endTime = convertLogTime(endTime);
			}
			
			TestLog log = new TestLog();
			log.setDevSn(devSn);
			log.setUser(username);
			log.setType(logType);
			log.setTesttype(testType);
			req.setCharacterEncoding("UTF-8");
			resp.setContentType("application/x-download");
			fileName = URLEncoder.encode(fileName, "UTF-8");
			resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			HSSFWorkbook wb = logSer.getFileToBackUp
					(log,_startTime,_endTime , pageNo , pageSize,req);
			ServletOutputStream outputStream = resp.getOutputStream();
			wb.write( outputStream );
			outputStream.close();
	} catch (Exception e) {
		logger.error("" , e);
	}
	
	return null;
	}
	
}



